package flag

import (
	"fmt"
	"gin_framework/global"
	"gin_framework/models"
	ctype "gin_framework/models/type"
	"gin_framework/utils/pwd"
)

func CreateUser(permission string) {
	var (
		userName   string
		nickName   string
		password   string
		rePassword string
		email      string
	)
	fmt.Printf("请输入用户名: ")
	fmt.Scan(&userName)
	fmt.Printf("请输入呢称: ")
	fmt.Scan(&nickName)
	fmt.Printf("请输入密码: ")
	fmt.Scan(&password)
	fmt.Printf("请再次输入密码: ")
	fmt.Scan(&rePassword)
	fmt.Printf("请输入邮件: ")
	fmt.Scanln(&email)
	// 判断用户名是否存在
	var userModel models.UserModel
	err := global.DB.Take(&userModel, "user_name = ?", userName).Error
	if err.Error() != "record not found" {
		fmt.Println(err)
		global.Log.Error("用户已存在,请重新输入")
		return
	}
	//校验两次密码
	if password != rePassword {
		global.Log.Error("两次输入密码不一致~")
		return
	}
	// 密码加密
	hashPassword := pwd.HashPwd(password)
	role := ctype.PermissionUser
	if permission == "admin" {
		role = models.PermissionAdmin
	}
	avatar := "uploads/avater.png"
	err = global.DB.Create(&models.UserModel{
		NickName: nickName,
		UserName: userName,
		Password: hashPassword,
		Avatar:   avatar,
		Email:    email,
		Role:     role,
		IP:       "127.0.0.1",
		Addr:     "内网地址",
	}).Error
	if err != nil {
		global.Log.Error(err)
		return
	}
	global.Log.Infof("用户%s创建成功!", userName)
}
